package com.example.service

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.service.service.MyIntentService
import com.example.service.service.OneService

class MainActivity : AppCompatActivity() {
    companion object{
        private const val TAG = "MainActivity"
    }
    lateinit var mIntent:Intent
    lateinit var binder:OneService.OneBinder
    /**
     * activity和service链接
     */
    val connection:ServiceConnection = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.d(TAG, "绑定成功: ")
            binder = service as OneService.OneBinder
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(TAG, "绑定失败: ")
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        mIntent = Intent(this, OneService::class.java)
    }

    fun start(view: View) {
        startService(mIntent)
    }
    fun stop(view: View) {
        stopService(mIntent)
    }
    fun bind(view: View) {
        bindService(mIntent,connection, BIND_AUTO_CREATE)
    }
    fun unbind(view: View) {
        unbindService(connection)
    }

    fun add(view: View) {
        val num = binder.add(4,8)
        Log.d(TAG, "add: $num")
    }

    fun download(view: View) {
        val intent = Intent(this, MyIntentService::class.java)
        startService(intent) //启动，下载完成后会自动结束服务
    }
}